﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Web.UI;

public partial class Main_Inventory_SaleInvoiceBillLevel : System.Web.UI.Page
{

    Datautility DU = new Datautility();
    string strsql = "";
    DataTable DTMain = new DataTable();
    int controlCounterBillLevel = 5;
    List<string> LstCountBillLevel;
    List<string> LstItemBillLevel;
    List<string> LstUnitBillLevel;
    List<string> LstUnitIdBillLevel;
    List<string> LstQtyBillLevel;
    List<string> LstRateBillLevel;
    List<string> LstButtonBillLevel;
    List<string> LstLocationBillLevel;
    List<string> LstTaxRateBillLevel;
    List<string> LstTaxAmtBillLevel;
    List<string> LstTotalAmountBillLevel;

    //protected override void LoadViewState(object savedState)
    //{
    //    base.LoadViewState(savedState);        
    //    OverrideAddMoreBillLevel();
    //}    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            //ScriptManager.RegisterStartupScript(Page, this.GetType(), "redirect", "window.open('../../login.aspx','_parent');", true);
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (Request.QueryString["action"] != null)
        {
            if (Request.QueryString["action"].ToString() == "addnew")
            {
                PnlAddNew.Visible = true;
                if (!IsPostBack)
                {
                    #region Initialized list for bill level tax

                    LstCountBillLevel = new List<string>();
                    ViewState["LstCountBillLevel"] = LstCountBillLevel;

                    LstItemBillLevel = new List<string>();
                    ViewState["LstItemBillLevel"] = LstItemBillLevel;

                    LstUnitBillLevel = new List<string>();
                    ViewState["LstUnitBillLevel"] = LstUnitBillLevel;

                    LstUnitIdBillLevel = new List<string>();
                    ViewState["LstUnitIdBillLevel"] = LstUnitIdBillLevel;

                    LstQtyBillLevel = new List<string>();
                    ViewState["LstQtyBillLevel"] = LstQtyBillLevel;

                    LstRateBillLevel = new List<string>();
                    ViewState["LstRateBillLevel"] = LstRateBillLevel;

                    LstButtonBillLevel = new List<string>();
                    ViewState["LstButtonBillLevel"] = LstButtonBillLevel;

                    LstLocationBillLevel = new List<string>();
                    ViewState["LstLocationBillLevel"] = LstLocationBillLevel;

                    LstTaxRateBillLevel = new List<string>();
                    ViewState["LstTaxRateBillLevel"] = LstTaxRateBillLevel;

                    LstTaxAmtBillLevel = new List<string>();
                    ViewState["LstTaxAmtBillLevel"] = LstTaxAmtBillLevel;

                    LstTotalAmountBillLevel = new List<string>();
                    ViewState["LstTotalAmountBillLevel"] = LstTotalAmountBillLevel;
                    #endregion

                    BindTranFormat();
                    BindTaxGroup();
                    BindCustomer();
                    BindItems(tblBillLevel, "ddlItemBillLevel");
                    BindSalesLedger(ddlSaleLedger);
                    BindTaxLedger(ddlSaleTaxLedger);
                    BindJavaScriptBillLevel();
                }
                OverrideAddMoreBillLevel();
                BindJavaScriptBillLevel();
            }
            else if (Request.QueryString["action"].ToString() == "view")
            {
                if (!IsPostBack)
                {
                    PnlView.Visible = true;
                    BindGrdSaleInvoice();
                }
            }
        }
    }


    #region Common function for Tax at Bill Level & Tax At Item Level
    protected void BindTaxGroup()//Bind Tax Group
    {
        DataTable DT = DU.getdatausingprocedure("USP_ACC_GetSalesMainClass");
        if (DT.Rows.Count > 0)
        {
            ddlTaxGroup.DataSource = DT;
            ddlTaxGroup.DataTextField = "MAINCLASSNAME";
            ddlTaxGroup.DataValueField = "MAINCLASSID";
            ddlTaxGroup.DataBind();
            ddlTaxGroup.Items.Insert(0, new ListItem("", "0"));
        }
    }
    protected void BindTranFormat()//Bind Transaction format 
    {
        SqlParameter[] sparam =
                            {
                                new SqlParameter("@TranType","1")
                            };
        DataTable DT = DU.getdatausingprocedure("USP_IVR_GetTransactionFormat", sparam);
        if (DT.Rows.Count > 0)
        {
            ddlFormat.DataSource = DT;
            ddlFormat.DataTextField = "FormatName";
            ddlFormat.DataValueField = "Tfoid";
            ddlFormat.DataBind();
            Bind_VoucherNo();
        }
    }
    protected void BindCustomer()//Bind Customer to ddlCustomer
    {
        DataTable DT = DU.getdatausingprocedure("USP_ACC_GetLedgerForPurchaseInvoice");
        if (DT.Rows.Count > 0)
        {
            ddlCustomer.DataSource = DT;
            ddlCustomer.DataTextField = "LNAME";
            ddlCustomer.DataValueField = "LID";
            ddlCustomer.DataBind();
        }
    }
    protected void BindItems(HtmlTable tblId, string ddlItemId)// A Common function for getting Item details from database
    {
        int count = tblId.Rows.Count;
        for (int i = 1; i < count; i++)
        {
            DropDownList ddlItem = (DropDownList)tblId.Rows[i].FindControl(ddlItemId + i.ToString());
            BindAllItemDropdownlist(ddlItem);
        }
    }
    protected void BindAllItemDropdownlist(DropDownList ddl)//common function for bind dropdown list from item table
    {
        if (ddlFormat.SelectedValue != "0")
        {
            SqlParameter[] sparam =
                                   {
                                       new SqlParameter("@TFOID",ddlFormat.SelectedValue)
                                   };
            DataTable DTItem = DU.getdatausingprocedure("USP_IVR_GetItemForPurchaseInvoice", sparam);
            if (DTItem.Rows.Count > 0)
            {
                ddl.DataSource = DTItem;
                ddl.DataTextField = "ITMNAME";
                ddl.DataValueField = "ITMID";
                ddl.DataBind();
                ddl.Items.Insert(0, new ListItem("-Select Item-", "0"));
            }
        }
        else
        {
            ddl.Items.Clear();
        }
    }
    protected bool isBatchEnabled(string ItemId)//A common function for check item batch enabled or not
    {
        bool Flag = true;
        if (ItemId.ToString() != string.Empty)
        {
            strsql = "Select ITMBATCH from IVR_ITEM Where ITMID='" + ItemId.ToString() + "'";
            DataTable DT = DU.getdata(strsql);
            if (DT.Rows.Count > 0)
            {
                if (Convert.ToDouble(DT.Rows[0]["ITMBATCH"]) > 0)
                {
                    Flag = true;
                }
                else
                {
                    Flag = false;
                }
            }
        }
        return Flag;
    }
    protected bool isWarrantyEnabled(string ItemId)//A common function for check item warranty enabled or not
    {
        bool Flag = true;
        if (ItemId.ToString() != string.Empty)
        {
            strsql = "Select ITMBATCH, ITMBATCHOPT from IVR_ITEM Where ITMID='" + ItemId.ToString() + "'";
            DataTable DT = DU.getdata(strsql);
            if (DT.Rows.Count > 0)
            {
                if (Convert.ToDouble(DT.Rows[0]["ITMBATCH"]) > 0 && Convert.ToDouble(DT.Rows[0]["ITMBATCHOPT"]) == 1)
                {
                    Flag = true;
                }
                else
                {
                    Flag = false;
                }
            }
        }
        return Flag;
    }
    protected void BindAllTaxDropdownlist(DropDownList ddlTaxType)//Function for bind subtax group
    {
        strsql = "select SUBCLASSNAME,SUBCLASSID from UVW_ACC_TaxMaster where mainclassid='" + ddlTaxGroup.SelectedValue + "'";
        DataTable DT = DU.getdata(strsql);
        if (DT.Rows.Count > 0)
        {
            ddlTaxType.DataSource = DT;
            ddlTaxType.DataTextField = "SUBCLASSNAME";
            ddlTaxType.DataValueField = "SUBCLASSID";
            ddlTaxType.DataBind();
            ddlTaxType.Items.Insert(0, new ListItem("-Select-", "0"));
        }
    }
    protected void BindTaxLedger(DropDownList ddl)//Common function for bind Tax ledger for transaction
    {

        DataTable DT = DU.getdatausingprocedure("USP_IVR_GetTaxLedgerforPurchaseInvoice");
        if (DT.Rows.Count > 0)
        {
            ddl.DataSource = DT;
            ddl.DataTextField = "Lname";
            ddl.DataValueField = "LID";
            ddl.DataBind();
            ddl.Items.Insert(0, new ListItem("- Select Ledger -", "0"));
        }
        else
        {
            ddl.Items.Clear();
        }
    }
    protected void BindSalesLedger(DropDownList ddl)//Common function for bind Sales ledger for transaction
    {
        DataTable DT = DU.getdatausingprocedure("USP_ACC_GetLedgerForSalesInvoice");
        if (DT.Rows.Count > 0)
        {
            ddl.DataSource = DT;
            ddl.DataTextField = "Lname";
            ddl.DataValueField = "LID";
            ddl.DataBind();
            ddl.Items.Insert(0, new ListItem("- Select Ledger -", "0"));
        }
        else
        {
            ddl.Items.Clear();
        }
    }
    protected void ddlTaxGroup_OnSelectedIndexChanged(object sender, EventArgs e)//Bind Subtax Ledger
    {
        BindAllTaxDropdownlist(ddlVatBillLevel);
    }
    protected void InsertTranOthers(string tranId)
    {
        if (tranId.ToString() != string.Empty)
        {
            SqlParameter[] sparam =
                                    {
                                        new SqlParameter("@TRNID",tranId.ToString()),
                                        new SqlParameter("@PREPAREDBY",txtPreparedBy.Text.Trim()),
                                        new SqlParameter("@CHECKEDBY",txtCheckedBy.Text.Trim()),
                                        new SqlParameter("@AUTHRSDSIGNAT",txtSignatory.Text.Trim()),
                                        new SqlParameter("@NARRATION",txtNarration.Text.Trim()),
                                        new SqlParameter("@REMARKS",txtRemark.Text.Trim())                                        
                                    };
            DU.executeprocedure("USP_IVR_SaveTranOthers", sparam);
        }
    }
    protected void InsertTranDelivery(string tranId)
    {
        if (tranId.ToString() != string.Empty)
        {
            string strDeliveryDate = "1/1/1900";
            if (txtDeliveryDate.Text != string.Empty)
            {
                string[] str = txtDeliveryDate.Text.ToString().Split('/');
                strDeliveryDate = str[1] + "/" + str[0] + "/" + str[2];
            }
            SqlParameter[] sparam =
                                    {
                                        new SqlParameter("@TRNID",tranId.ToString()),
                                        new SqlParameter("@MODEOFDELIVERY",txtDeliveryMode.Text.Trim()),
                                        new SqlParameter("@DELIVERYDATE",strDeliveryDate) ,
                                        new SqlParameter("@DOCUMENTNUM",txtDocumentNo.Text.Trim()),
                                        new SqlParameter("@VEHICLENUM",txtVehicle.Text.Trim()),
                                        new SqlParameter("@TRANSPORTNAME",txtTransporter.Text.Trim())                                                                              
                                    };
            DU.executeprocedure("USP_IVR_SaveTranDelivery", sparam);
        }
    }
    protected void GetBillingType()
    {
        if (ddlFormat.SelectedValue != "0")
        {
            strsql = "SELECT TAXATITEM FROM IVR_TRANFORMAT WHERE TFOID='" + ddlFormat.SelectedValue + "";
            DataTable DT = DU.getdata(strsql);
            if (DT.Rows.Count > 0)
            {
                if (DT.Rows[0]["TAXATITEM"].ToString() == "True")
                {
                    hidTaxLevel.Value = "Item Level";
                }
                else
                {
                    hidTaxLevel.Value = "Bill Level";
                }
            }
        }
    }
    protected void ddlFormat_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        Bind_VoucherNo();
    }

    protected void Bind_VoucherNo()
    {
        if (ddlFormat.SelectedValue != "0")
        {
            SqlParameter[] sparam =
                                 {
                                     new SqlParameter("@TFOID",ddlFormat.SelectedValue),
                                     new SqlParameter("@FINYEAR","2010")
                                 };
            DataTable DTNum = DU.getdatausingprocedure("USP_IVR_GetMaxVoucherNumber", sparam);
            if (DTNum.Rows.Count > 0)
            {

                txtPrefix.Text = DTNum.Rows[0]["NUMPREFIX"].ToString();
                txtVoucher.Text = DTNum.Rows[0]["NUMSTART"].ToString();
                txtSuffix.Text = DTNum.Rows[0]["NUMSUFFIX"].ToString();
            }
        }
    }

    #endregion
    #region functions for tax at bill level
    protected void BindJavaScriptBillLevel()//A common function for add javascript attribute to btn quantity
    {
        int intCount = Convert.ToInt32(hidControlBillLevel.Value);
        for (int i = 1; i <= intCount; i++)
        {
            DropDownList ddlItemBillLevel = (DropDownList)tblBillLevel.Rows[i].FindControl("ddlItemBillLevel" + i.ToString());
            TextBox txtQuantityBillLevel = (TextBox)tblBillLevel.Rows[i].FindControl("txtQuantityBillLevel" + i.ToString());
            HiddenField hidLocationBillLevel = (HiddenField)tblBillLevel.Rows[i].FindControl("hidLocationBillLevel" + i.ToString());
            Button btnQtyBillLevel = (Button)tblBillLevel.Rows[i].FindControl("btnQtyBillLevel" + i.ToString());
            btnQtyBillLevel.Attributes.Add("onclick", "return GetQuantity('" + ddlItemBillLevel.SelectedValue + "', '" + txtQuantityBillLevel.ClientID.ToString() + "', '" + hidLocationBillLevel.ClientID.ToString() + "');");
        }
    }
    protected void ddlItemBillLevel_SelectedIndexChanged(object sender, EventArgs e)//A common event method for getting UOM for Tax On Bill Level 
    {

        DropDownList ddl = (DropDownList)sender;
        string ddlid = ddl.ID.ToString().Substring(16);
        int rowIndex = Convert.ToInt32(ddlid.ToString());
        TextBox txtUnitBillLevel = (TextBox)tblBillLevel.Rows[rowIndex].FindControl("txtUnitBillLevel" + rowIndex.ToString());
        TextBox txtQuantityBillLevel = (TextBox)tblBillLevel.Rows[rowIndex].FindControl("txtQuantityBillLevel" + rowIndex.ToString());
        TextBox txtRateBillLevel = (TextBox)tblBillLevel.Rows[rowIndex].FindControl("txtRateBillLevel" + rowIndex.ToString());
        TextBox txtAmountBillLevel = (TextBox)tblBillLevel.Rows[rowIndex].FindControl("txtAmountBillLevel" + rowIndex.ToString());
        HiddenField hidUnitIdBillLevel = (HiddenField)tblBillLevel.Rows[rowIndex].FindControl("hidUnitIdBillLevel" + rowIndex.ToString());
        HiddenField hidTaxRateBillLevel = (HiddenField)tblBillLevel.Rows[rowIndex].FindControl("hidTaxRateBillLevel" + rowIndex.ToString());
        HiddenField hidTaxAmtBillLevel = (HiddenField)tblBillLevel.Rows[rowIndex].FindControl("hidTaxAmtBillLevel" + rowIndex.ToString());
        HiddenField hidLocationBillLevel = (HiddenField)tblBillLevel.Rows[rowIndex].FindControl("hidLocationBillLevel" + rowIndex.ToString());

        if (ddl.SelectedValue != "0")
        {
            txtUnitBillLevel.Text = "";
            txtQuantityBillLevel.Text = "";
            txtRateBillLevel.Text = "";
            txtAmountBillLevel.Text = "";
            hidUnitIdBillLevel.Value = "";
            hidTaxAmtBillLevel.Value = "0";
            hidTaxRateBillLevel.Value = "0";
            hidLocationBillLevel.Value = "";
            string sql = "select UOMNAME,UOMID from IVR_UOM inner join IVR_ITEM on IVR_UOM.UOMID=IVR_ITEM.PRIMARY_UOMID where IVR_ITEM.ITMID='" + ddl.SelectedValue + "'";
            DataTable DT = DU.getdata(sql);
            txtUnitBillLevel.Text = DT.Rows[0]["UOMNAME"].ToString();
            hidUnitIdBillLevel.Value = DT.Rows[0]["UOMID"].ToString();
        }
        else
        {

            txtUnitBillLevel.Text = "";
            txtQuantityBillLevel.Text = "";
            txtRateBillLevel.Text = "";
            txtAmountBillLevel.Text = "";
            hidUnitIdBillLevel.Value = "";
            hidTaxAmtBillLevel.Value = "0";
            hidTaxRateBillLevel.Value = "0";
            hidLocationBillLevel.Value = "";
        }
        ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "CalculateAmtBillLevel();", true);

    }
    protected void AddMoreBillLevel()//Add more row for tax at bill level
    {
        controlCounterBillLevel++;
        HtmlTableRow HTRow = new HtmlTableRow();

        HtmlTableCell HTCell1 = new HtmlTableCell();
        DropDownList ddlItemBillLevel = new DropDownList();
        ddlItemBillLevel.ID = "ddlItemBillLevel" + controlCounterBillLevel.ToString();
        ddlItemBillLevel.CssClass = "dropdown";
        ddlItemBillLevel.Width = Unit.Percentage(98);
        BindAllItemDropdownlist(ddlItemBillLevel);
        ddlItemBillLevel.AutoPostBack = true;
        ddlItemBillLevel.SelectedIndexChanged += new EventHandler(ddlItemBillLevel_SelectedIndexChanged);
        HTCell1.Controls.Add(ddlItemBillLevel);
        LstItemBillLevel.Add(ddlItemBillLevel.ID);
        LstCountBillLevel.Add(controlCounterBillLevel.ToString());

        HtmlTableCell HTCell2 = new HtmlTableCell();
        TextBox txtUnitBillLevel = new TextBox();
        txtUnitBillLevel.ID = "txtUnitBillLevel" + controlCounterBillLevel.ToString();
        txtUnitBillLevel.CssClass = "input";
        txtUnitBillLevel.Width = Unit.Percentage(98);
        HiddenField hidUnitIdBillLevel = new HiddenField();
        hidUnitIdBillLevel.ID = "hidUnitIdBillLevel" + controlCounterBillLevel.ToString();
        HTCell2.Controls.Add(txtUnitBillLevel);
        HTCell2.Controls.Add(hidUnitIdBillLevel);
        LstUnitBillLevel.Add(txtUnitBillLevel.ID);
        LstUnitIdBillLevel.Add(hidUnitIdBillLevel.ID);

        HtmlTableCell HTCell3 = new HtmlTableCell();
        TextBox txtQuantityBillLevel = new TextBox();
        txtQuantityBillLevel.ID = "txtQuantityBillLevel" + controlCounterBillLevel.ToString();
        txtQuantityBillLevel.CssClass = "inputnumber";
        txtQuantityBillLevel.Width = Unit.Percentage(98);
        HTCell3.Controls.Add(txtQuantityBillLevel);
        LstQtyBillLevel.Add(txtQuantityBillLevel.ID);

        HtmlTableCell HTCell4 = new HtmlTableCell();
        Button btnQtyBillLevel = new Button();
        btnQtyBillLevel.ID = "btnQtyBillLevel" + controlCounterBillLevel.ToString();
        btnQtyBillLevel.Text = "...";
        btnQtyBillLevel.CssClass = "button";
        btnQtyBillLevel.Width = Unit.Percentage(98);
        HiddenField hidLocationBillLevel = new HiddenField();
        hidLocationBillLevel.ID = "hidLocationBillLevel" + controlCounterBillLevel.ToString();
        HTCell4.Controls.Add(btnQtyBillLevel);
        HTCell4.Controls.Add(hidLocationBillLevel);
        LstButtonBillLevel.Add(btnQtyBillLevel.ID);
        LstLocationBillLevel.Add(hidLocationBillLevel.ID);

        HtmlTableCell HTCell5 = new HtmlTableCell();
        TextBox txtRateBillLevel = new TextBox();
        txtRateBillLevel.ID = "txtRateBillLevel" + controlCounterBillLevel.ToString();
        txtRateBillLevel.CssClass = "inputnumber";
        txtRateBillLevel.Width = Unit.Percentage(98);
        HiddenField hidTaxRateBillLevel = new HiddenField();
        hidTaxRateBillLevel.ID = "hidTaxRateBillLevel" + controlCounterBillLevel.ToString();
        HiddenField hidTaxAmtBillLevel = new HiddenField();
        hidTaxAmtBillLevel.ID = "hidTaxAmtBillLevel" + controlCounterBillLevel.ToString();
        HTCell5.Controls.Add(txtRateBillLevel);
        HTCell5.Controls.Add(hidTaxRateBillLevel);
        HTCell5.Controls.Add(hidTaxAmtBillLevel);
        LstRateBillLevel.Add(txtRateBillLevel.ID);
        LstTaxRateBillLevel.Add(hidTaxRateBillLevel.ID);
        LstTaxAmtBillLevel.Add(hidTaxAmtBillLevel.ID);

        HtmlTableCell HTCell6 = new HtmlTableCell();
        TextBox txtAmountBillLevel = new TextBox();
        txtAmountBillLevel.ID = "txtAmountBillLevel" + controlCounterBillLevel.ToString();
        txtAmountBillLevel.CssClass = "inputnumber";
        txtAmountBillLevel.Width = Unit.Percentage(98);
        HTCell6.Controls.Add(txtAmountBillLevel);
        LstTotalAmountBillLevel.Add(txtAmountBillLevel.ID);


        HTRow.Cells.Add(HTCell1);
        HTRow.Cells.Add(HTCell2);
        HTRow.Cells.Add(HTCell3);
        HTRow.Cells.Add(HTCell4);
        HTRow.Cells.Add(HTCell5);
        HTRow.Cells.Add(HTCell6);

        tblBillLevel.Rows.Add(HTRow);


        ViewState["LstCountBillLevel"] = LstCountBillLevel;
        ViewState["LstItemBillLevel"] = LstItemBillLevel;
        ViewState["LstUnitBillLevel"] = LstUnitBillLevel;
        ViewState["LstUnitIdBillLevel"] = LstUnitIdBillLevel;
        ViewState["LstQtyBillLevel"] = LstQtyBillLevel;
        ViewState["LstRateBillLevel"] = LstRateBillLevel;
        ViewState["LstButtonBillLevel"] = LstButtonBillLevel;
        ViewState["LstLocationBillLevel"] = LstLocationBillLevel;
        ViewState["LstTaxRateBillLevel"] = LstTaxRateBillLevel;
        ViewState["LstTaxAmtBillLevel"] = LstTaxAmtBillLevel;
        ViewState["LstTotalAmountBillLevel"] = LstTotalAmountBillLevel;
        //lblMsg.Text += ((List<string>)ViewState["LstCountBillLevel"]).Count.ToString();

        hidControlBillLevel.Value = controlCounterBillLevel.ToString();
    }

    protected void OverrideAddMoreBillLevel()//Override View State for Added More Row to bill level tax
    {

        LstCountBillLevel = (List<string>)ViewState["LstCountBillLevel"];
        LstItemBillLevel = (List<string>)ViewState["LstItemBillLevel"];
        LstUnitBillLevel = (List<string>)ViewState["LstUnitBillLevel"];
        LstUnitIdBillLevel = (List<string>)ViewState["LstUnitIdBillLevel"];
        LstQtyBillLevel = (List<string>)ViewState["LstQtyBillLevel"];
        LstRateBillLevel = (List<string>)ViewState["LstRateBillLevel"];
        LstButtonBillLevel = (List<string>)ViewState["LstButtonBillLevel"];
        LstLocationBillLevel = (List<string>)ViewState["LstLocationBillLevel"];
        LstTaxRateBillLevel = (List<string>)ViewState["LstTaxRateBillLevel"];
        LstTaxAmtBillLevel = (List<string>)ViewState["LstTaxAmtBillLevel"];
        LstTotalAmountBillLevel = (List<string>)ViewState["LstTotalAmountBillLevel"];
        if (LstCountBillLevel != null)
        {
            int intCount = Convert.ToInt32(LstCountBillLevel.Count);
            for (int i = 0; i < intCount; i++)
            {
                controlCounterBillLevel++;
                HtmlTableRow HTRow = new HtmlTableRow();

                HtmlTableCell HTCell1 = new HtmlTableCell();
                DropDownList ddlItemBillLevel = new DropDownList();
                ddlItemBillLevel.ID = LstItemBillLevel[i].ToString();
                ddlItemBillLevel.CssClass = "dropdown";
                ddlItemBillLevel.Width = Unit.Percentage(98);
                BindAllItemDropdownlist(ddlItemBillLevel);
                ddlItemBillLevel.AutoPostBack = true;
                ddlItemBillLevel.SelectedIndexChanged += new EventHandler(ddlItemBillLevel_SelectedIndexChanged);
                HTCell1.Controls.Add(ddlItemBillLevel);

                HtmlTableCell HTCell2 = new HtmlTableCell();
                TextBox txtUnitBillLevel = new TextBox();
                txtUnitBillLevel.ID = LstUnitBillLevel[i].ToString();
                txtUnitBillLevel.CssClass = "input";
                txtUnitBillLevel.Width = Unit.Percentage(98);
                HiddenField hidUnitIdBillLevel = new HiddenField();
                hidUnitIdBillLevel.ID = LstUnitIdBillLevel[i].ToString();
                HTCell2.Controls.Add(txtUnitBillLevel);
                HTCell2.Controls.Add(hidUnitIdBillLevel);


                HtmlTableCell HTCell3 = new HtmlTableCell();
                TextBox txtQuantityBillLevel = new TextBox();
                txtQuantityBillLevel.ID = LstQtyBillLevel[i].ToString();
                txtQuantityBillLevel.CssClass = "inputnumber";
                txtQuantityBillLevel.Width = Unit.Percentage(98);
                HTCell3.Controls.Add(txtQuantityBillLevel);

                HtmlTableCell HTCell4 = new HtmlTableCell();
                Button btnQtyBillLevel = new Button();
                btnQtyBillLevel.ID = LstButtonBillLevel[i].ToString();
                btnQtyBillLevel.Text = "...";
                btnQtyBillLevel.CssClass = "button";
                btnQtyBillLevel.Width = Unit.Percentage(98);
                HiddenField hidLocationBillLevel = new HiddenField();
                hidLocationBillLevel.ID = LstLocationBillLevel[i].ToString();
                HTCell4.Controls.Add(btnQtyBillLevel);
                HTCell4.Controls.Add(hidLocationBillLevel);

                HtmlTableCell HTCell5 = new HtmlTableCell();
                TextBox txtRateBillLevel = new TextBox();
                txtRateBillLevel.ID = LstRateBillLevel[i].ToString();
                txtRateBillLevel.CssClass = "inputnumber";
                txtRateBillLevel.Width = Unit.Percentage(98);
                HiddenField hidTaxRateBillLevel = new HiddenField();
                hidTaxRateBillLevel.ID = LstTaxRateBillLevel[i].ToString();
                HiddenField hidTaxAmtBillLevel = new HiddenField();
                hidTaxAmtBillLevel.ID = LstTaxAmtBillLevel[i].ToString();
                HTCell5.Controls.Add(txtRateBillLevel);
                HTCell5.Controls.Add(hidTaxRateBillLevel);
                HTCell5.Controls.Add(hidTaxAmtBillLevel);

                HtmlTableCell HTCell6 = new HtmlTableCell();
                TextBox txtAmountBillLevel = new TextBox();
                txtAmountBillLevel.ID = LstTotalAmountBillLevel[i].ToString();
                txtAmountBillLevel.CssClass = "inputnumber";
                txtAmountBillLevel.Width = Unit.Percentage(98);
                HTCell6.Controls.Add(txtAmountBillLevel);


                HTRow.Cells.Add(HTCell1);
                HTRow.Cells.Add(HTCell2);
                HTRow.Cells.Add(HTCell3);
                HTRow.Cells.Add(HTCell4);
                HTRow.Cells.Add(HTCell5);
                HTRow.Cells.Add(HTCell6);

                tblBillLevel.Rows.Add(HTRow);

            }
        }

    }
    protected void btnAddMoreBillLevel_Click(object sender, EventArgs e)
    {
        AddMoreBillLevel();
        BindJavaScriptBillLevel();
    }
    protected void ddlVatBillLevel_OnSelectedIndexChanged(object sender, EventArgs e)//Get tax rate from sub tax group 
    {
        double taxRate = 0;
        if (ddlVatBillLevel.SelectedValue != "0")
        {

            strsql = "SELECT DEFTAXRATE FROM UVW_ACC_TAXMASTER WHERE MAINCLASSID='" + ddlTaxGroup.SelectedValue + "' AND SUBCLASSID='" + ddlVatBillLevel.SelectedValue + "'";
            DataTable DT = DU.getdata(strsql);
            if (DT.Rows.Count > 0)
            {
                if (DT.Rows[0]["DEFTAXRATE"].ToString() != string.Empty)
                {
                    taxRate = Convert.ToDouble(DT.Rows[0]["DEFTAXRATE"]);
                }
            }
        }
        int rowCount = Convert.ToInt32(hidControlBillLevel.Value);
        for (int i = 1; i <= rowCount; i++)
        {
            HiddenField hidTaxRateBillLevel = (HiddenField)tblBillLevel.Rows[i].FindControl("hidTaxRateBillLevel" + i.ToString());
            hidTaxRateBillLevel.Value = taxRate.ToString();
        }
        hidTaxRateBillLevelMain.Value = taxRate.ToString();
        ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "CalculateAmtBillLevel();", true);

    }

    protected string InsertVouchersBillLevel()
    {
        string strTransactionTypeID = string.Empty;
        string strFinYear = string.Empty;
        string strTransDate = string.Empty;
        string strRefId = string.Empty;
        int intResult = 0;
        try
        {
            SqlParameter[] sparam = {
                                    new SqlParameter("@PARENTTYPEID","10"),
                                    new SqlParameter("@BILLFORMATID",ddlFormat.SelectedValue),
                                    new SqlParameter("@MODULETYPE","2")
                                };
            DataTable DTRef = DU.getdatausingprocedure("USP_ACC_GetTransactionSettingBasedOnFormat", sparam);
            if (DTRef.Rows.Count > 0)
            {
                strTransactionTypeID = DTRef.Rows[0]["TYPEID"].ToString();
            }
            lblMsg.Text = strTransactionTypeID.ToString();
            strsql = "Select * from MAS_FINYEAR";
            DataTable DTFinYear = DU.getdata(strsql);
            if (DTFinYear.Rows.Count > 0)
            {
                strFinYear = DTFinYear.Rows[0]["FINYEAR"].ToString();
            }

            if (txtDate.Text.ToString() != string.Empty)
            {
                string[] str = txtDate.Text.ToString().Split('/');
                strTransDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
            }
            if (strTransactionTypeID.ToString() != string.Empty)
            {
                SqlParameter[] sparam1 = { 
                                    new SqlParameter("@TransactionTypeID",strTransactionTypeID.ToString()),
                                    new SqlParameter("@TransactionNumber",txtVoucher.Text.Trim()),
                                    new SqlParameter("@FinYear",strFinYear.ToString()),
                                    new SqlParameter("@ReferenceNumber",txtBillRef1.Text.Trim()),
                                    new SqlParameter("@IsCashVoucher","0"),
                                    new SqlParameter("@TransactionDate",strTransDate.ToString()),
                                    new SqlParameter("@CreditDays",txtCreditDay.Text.Trim()),
                                    new SqlParameter("@CreatedBy",Session["username"].ToString()),
                                    new SqlParameter("@IsCancelled","0"),
                                    new SqlParameter("@CostCentreClassID","0")
                                };
                intResult = DU.executeprocedure("USP_ACC_SaveTransaction", sparam1);

                if (intResult > 0)
                {
                    strsql = "Select Ident_Current('ACC_VOUCHERS') as TranId";
                    DataTable DTTranid = DU.getdata(strsql);
                    if (DTTranid.Rows.Count > 0)
                    {
                        strRefId = DTTranid.Rows[0]["TranId"].ToString();
                        InsertVoucherDetailsBillLevel(DTTranid.Rows[0]["TranId"].ToString());
                    }
                }
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message.ToString();
        }

        return strRefId.ToString();
    }
    protected void InsertVoucherDetailsBillLevel(string TranId)
    {
        if (TranId.ToString() != string.Empty)
        {
            if (ddlCustomer.SelectedValue != "0")
            {
                decimal Amount = 0;
                if (txtGrandTotalBillLevel.Text != string.Empty)
                {
                    decimal Amt = Convert.ToDecimal(txtGrandTotalBillLevel.Text.Trim());
                    Amount = 0 - Amt;
                }
                SqlParameter[] sparam = {
                                    new SqlParameter("@TransactionID",TranId.ToString()),
                                    new SqlParameter("@LedgerID",ddlCustomer.SelectedValue),
                                    new SqlParameter("@Amount",Amount.ToString()),
                                    new SqlParameter("@IsReconciled","0")
                                };

                int result = DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);
                if (result > 0)
                {
                    strsql = "Select Ident_Current('ACC_VOUDETAILS') as VouSerial";
                    DataTable DTVouSerial = DU.getdata(strsql);
                    if (DTVouSerial.Rows.Count > 0)
                    {
                        InsertReFDetails(DTVouSerial.Rows[0]["VouSerial"].ToString());
                    }
                }
            }
            if (ddlSaleLedger.SelectedValue != "0")
            {
                decimal Amount = 0;
                if (txtTaxableAmtBillLevel.Text != string.Empty)
                {
                    Amount = Convert.ToDecimal(txtTaxableAmtBillLevel.Text.Trim());
                }
                SqlParameter[] sparam = {
                                    new SqlParameter("@TransactionID",TranId.ToString()),
                                    new SqlParameter("@LedgerID",ddlSaleLedger.SelectedValue),
                                    new SqlParameter("@Amount",Amount.ToString()),
                                    new SqlParameter("@IsReconciled","0")
                                };
                DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);
            }
            if (ddlSaleTaxLedger.SelectedValue != "0")
            {
                decimal Amount = 0;
                if (txtVatBillLevel.Text != string.Empty)
                {
                    Amount = Convert.ToDecimal(txtVatBillLevel.Text.Trim());

                }
                SqlParameter[] sparam = {
                                    new SqlParameter("@TransactionID",TranId.ToString()),
                                    new SqlParameter("@LedgerID",ddlSaleTaxLedger.SelectedValue),
                                    new SqlParameter("@Amount",Amount.ToString()),
                                    new SqlParameter("@IsReconciled","0")
                                };
                DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);
            }
        }
    }
    protected void InsertReFDetails(string strVouSerial)
    {
        if (strVouSerial != string.Empty)
        {
            decimal Amount = 0;
            string strRefDate = string.Empty;
            string strRefferenceNo = string.Empty;
            if (txtDate.Text.ToString() != string.Empty)
            {
                string[] str = txtDate.Text.ToString().Split('/');
                strRefDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
            }
            if (txtGrandTotalBillLevel.Text != string.Empty)
            {
                decimal Amt = Convert.ToDecimal(txtGrandTotalBillLevel.Text.Trim());
                Amount = 0 - Amt;
            }
            strsql = "SELECT FORMATNAME FROM IVR_TRANFORMAT WHERE TFOID='" + ddlFormat.SelectedValue + "'";
            DataTable DTFormatName = DU.getdata(strsql);
            if (DTFormatName.Rows.Count > 0)
            {
                strRefferenceNo += DTFormatName.Rows[0]["FORMATNAME"].ToString() + " ";
                if (txtPrefix.Text != string.Empty)
                {
                    strRefferenceNo += txtPrefix.Text + "/";
                }
                strRefferenceNo += txtVoucher.Text;
                if (txtSuffix.Text != string.Empty)
                {
                    strRefferenceNo += "/" + txtSuffix.Text;
                }

            }
            SqlParameter[] sparam1 = {
                                            new SqlParameter("@ReferenceSerial","0"),
                                            new SqlParameter("@ParentReference","0"),
                                            new SqlParameter("@TransactionSerial",strVouSerial),
                                            new SqlParameter("@ReferenceType","1"),
                                            new SqlParameter("@Reference",strRefferenceNo),
                                            new SqlParameter("@ReferenceDate",strRefDate),
                                            new SqlParameter("@CreditDays",txtCreditDay.Text),
                                            new SqlParameter("@ReferenceAmount",Amount),
                                            new SqlParameter("@IsTDSDeducted","0")
                                };
            DU.executeprocedure("USP_ACC_SaveReferenceDetails", sparam1);

        }
    }
    protected void InsertItemTranMainBillLevel(string strRefId)
    {
        if (strRefId.ToString() != string.Empty)
        {
            string strFinYear = string.Empty;
            string strTransDate = string.Empty;
            string strRefDate = "01/01/1900";
            string strEffectiveDate = string.Format("{0:MM/dd/yyyy}", System.DateTime.Now).ToString();
            strsql = "Select * from MAS_FINYEAR";
            DataTable DTFinYear = DU.getdata(strsql);
            if (DTFinYear.Rows.Count > 0)
            {
                strFinYear = DTFinYear.Rows[0]["FINYEAR"].ToString();
            }
            if (txtDate.Text.ToString() != string.Empty)
            {
                string[] str = txtDate.Text.ToString().Split('/');
                strTransDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
            }
            if (txtBillRef2.Text.ToString() != string.Empty)
            {
                string[] str = txtBillRef2.Text.ToString().Split('/');
                strRefDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
            }

            if (strRefId.ToString() != string.Empty)
            {
                SqlParameter[] sparam ={
                                   new SqlParameter("@TRANREFERENCEID",strRefId.ToString()),
                                   new SqlParameter("@TRANTYPEID","1"),
                                   new SqlParameter("@FINYEAR",strFinYear.ToString()),
                                   //new SqlParameter("@POID",Request.QueryString["Poid"].ToString()),
                                   //new SqlParameter("@INVOICENO",txtInvoiceNo.Text.Trim()),
                                   new SqlParameter("@TFOID",ddlFormat.SelectedValue),
                                   new SqlParameter("@TRNNUM",txtVoucher.Text.Trim()),
                                   new SqlParameter("@TRNDATE",strTransDate.ToString()),
                                   new SqlParameter("@VENDCUST_LID",ddlCustomer.SelectedValue),
                                   new SqlParameter("@TAX_MAINCLASSID",ddlTaxGroup.SelectedValue),
                                   new SqlParameter("@TRNSTATUS","1"),
                                   new SqlParameter("@EFFECTIVEDATE",strEffectiveDate.ToString()),
                                   new SqlParameter("@MODEOFPAY",rbtCashCredit.SelectedValue),
                                   new SqlParameter("@CREDITPERIOD",txtCreditDay.Text.Trim()),
                                   new SqlParameter("@REFNUM",txtBillRef1.Text.Trim()),
                                   new SqlParameter("@REFDATE",strRefDate.ToString()),
                                   new SqlParameter("@SURCHARGE","0"),                                   
                                   new SqlParameter("@CNAME",Session["username"].ToString())                                   
                               };
                int intResult = DU.executeprocedure("USP_IVR_SaveTranMain", sparam);
                if (intResult > 0)
                {
                    strsql = "Select Ident_Current('IVR_TRAN_MAIN') as TranId";
                    DataTable DTTranid = DU.getdata(strsql);
                    if (DTTranid.Rows.Count > 0)
                    {
                        InsertItemTranItemBillLevel(DTTranid.Rows[0]["TranId"].ToString());
                        InsertItemTranTotalBillLevel(DTTranid.Rows[0]["TranId"].ToString());
                        InsertTranDelivery(DTTranid.Rows[0]["TranId"].ToString());
                        InsertTranOthers(DTTranid.Rows[0]["TranId"].ToString());
                    }
                    lblMsg.Text = "Invoice Created";
                }
            }
        }
    }
    protected void InsertItemTranItemBillLevel(string strTranId)
    {
        if (strTranId.ToString() != string.Empty)
        {
            int intResult = 0;
            int intCount = Convert.ToInt32(hidControlBillLevel.Value);

            for (int i = 1; i <= intCount; i++)
            {

                DropDownList ddlItemBillLevel = (DropDownList)tblBillLevel.Rows[i].FindControl("ddlItemBillLevel" + i.ToString());
                HiddenField hidUnitIdBillLevel = (HiddenField)tblBillLevel.Rows[i].FindControl("hidUnitIdBillLevel" + i.ToString());
                TextBox txtQuantityBillLevel = (TextBox)tblBillLevel.Rows[i].FindControl("txtQuantityBillLevel" + i.ToString());
                TextBox txtRateBillLevel = (TextBox)tblBillLevel.Rows[i].FindControl("txtRateBillLevel" + i.ToString());
                HiddenField hidTaxRateBillLevel = (HiddenField)tblBillLevel.Rows[i].FindControl("hidTaxRateBillLevel" + i.ToString());
                HiddenField hidTaxAmtBillLevel = (HiddenField)tblBillLevel.Rows[i].FindControl("hidTaxAmtBillLevel" + i.ToString());
                TextBox txtAmountBillLevel = (TextBox)tblBillLevel.Rows[i].FindControl("txtAmountBillLevel" + i.ToString());

                if (hidTaxRateBillLevel.Value.ToString() == string.Empty)
                {
                    hidTaxRateBillLevel.Value = "0";
                }
                if (hidTaxAmtBillLevel.Value.ToString() == string.Empty)
                {
                    hidTaxAmtBillLevel.Value = "0";
                }

                if (txtQuantityBillLevel.Text != string.Empty && txtRateBillLevel.Text != string.Empty)
                {
                    double dblItemAmount = 0;
                    dblItemAmount = Convert.ToDouble(txtAmountBillLevel.Text) + Convert.ToDouble(hidTaxAmtBillLevel.Value);

                    SqlParameter[] sparam ={
                                   new SqlParameter("@TRNID",strTranId.ToString()),
                                   new SqlParameter("@ITMID",ddlItemBillLevel.SelectedValue ),
                                   new SqlParameter("@ITMQTY",txtQuantityBillLevel.Text.Trim()),
                                   new SqlParameter("@UOMID",hidUnitIdBillLevel.Value.ToString()),
                                   new SqlParameter("@RATE",txtRateBillLevel.Text.Trim()),
                                   new SqlParameter("@GROSSAMT",txtAmountBillLevel.Text.Trim()),
                                   new SqlParameter("@NETAMT",dblItemAmount),
                                   new SqlParameter("@TAXPER",hidTaxRateBillLevel.Value.ToString()),
                                   new SqlParameter("@TAXAMT",hidTaxAmtBillLevel.Value.ToString()),
                                   new SqlParameter("@ITMAMT",dblItemAmount)                                                                      
                               };
                    intResult = DU.executeprocedure("USP_IVR_SaveTranItem", sparam);
                }
                if (intResult > 0)
                {
                    strsql = "Select Ident_Current('IVR_TRAN_ITEM') as TITID";
                    DataTable DTTranid = DU.getdata(strsql);
                    if (DTTranid.Rows.Count > 0)
                    {
                        InsertItemTranDetailsBillLevel(strTranId, DTTranid.Rows[0]["TITID"].ToString(), i);
                    }
                    intResult = 0;
                }
            }
        }
    }
    protected void InsertItemTranDetailsBillLevel(string tranId, string tranItemId, int rowId)
    {
        if (tranId.ToString() != string.Empty && tranItemId.ToString() != string.Empty)
        {
            string strTransDate = string.Empty;
            if (txtDate.Text.ToString() != string.Empty)
            {
                string[] str = txtDate.Text.ToString().Split('/');
                strTransDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
            }
            DropDownList ddlItemBillLevel = (DropDownList)tblBillLevel.Rows[rowId].FindControl("ddlItemBillLevel" + rowId.ToString());
            TextBox txtRateBillLevel = (TextBox)tblBillLevel.Rows[rowId].FindControl("txtRateBillLevel" + rowId.ToString());
            HiddenField hidLocationBillLevel = (HiddenField)tblBillLevel.Rows[rowId].FindControl("hidLocationBillLevel" + rowId.ToString());
            TextBox txtQuantityBillLevel = (TextBox)tblBillLevel.Rows[rowId].FindControl("txtQuantityBillLevel" + rowId.ToString());

            if (txtQuantityBillLevel.Text != string.Empty && txtRateBillLevel.Text != string.Empty)
            {
                if (hidLocationBillLevel.Value.ToString() != string.Empty)
                {
                    if (isBatchEnabled(ddlItemBillLevel.SelectedValue) && isWarrantyEnabled(ddlItemBillLevel.SelectedValue))
                    {
                        List<string> lstLocationId = new List<string>();
                        List<string> lstBatchId = new List<string>();
                        List<string> lstLocationQty = new List<string>();
                        List<string> lstWarranty1 = new List<string>();
                        List<string> lstWarrantyDetails1 = new List<string>();
                        if (hidLocationBillLevel.Value.ToString().Contains("/") && hidLocationBillLevel.Value.ToString().Contains("|") && hidLocationBillLevel.Value.ToString().Contains(":"))
                        {
                            string[] strMainArray = hidLocationBillLevel.Value.ToString().Split('/');
                            foreach (string strSubArray in strMainArray)
                            {
                                string[] str = strSubArray.ToString().Split(',');
                                lstLocationId.Add(str[0].ToString());
                                string[] str1 = str[1].ToString().Split('|');
                                lstLocationQty.Add(str1[0].ToString());
                                string[] str2 = str1[1].ToString().Split(':');
                                lstBatchId.Add(str2[0].ToString());
                                string[] str3 = str2[1].ToString().Split(';');
                                lstWarranty1.Add(str3[0].ToString());
                                lstWarrantyDetails1.Add(str3[1].ToString());
                            }
                        }
                        else
                        {
                            string[] str = hidLocationBillLevel.Value.ToString().Split(',');
                            lstLocationId.Add(str[0].ToString());
                            string[] str1 = str[1].ToString().Split('|');
                            lstLocationQty.Add(str1[0].ToString());
                            string[] str2 = str1[1].ToString().Split(':');
                            lstBatchId.Add(str2[0].ToString());
                            string[] str3 = str2[1].ToString().Split(';');
                            lstWarranty1.Add(str3[0].ToString());
                            lstWarrantyDetails1.Add(str3[1].ToString());
                        }
                        if (lstLocationId != null)
                        {
                            int Count = Convert.ToInt32(lstLocationId.Count);
                            for (int j = 0; j < Count; j++)
                            {
                                SqlParameter[] sparam ={
                                                               new SqlParameter("@TITID",tranItemId.ToString()),
                                                               new SqlParameter("@WHSID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATID",lstBatchId[j].ToString()),
                                                               new SqlParameter("@DETQTY",lstLocationQty[j].ToString()),
                                                               new SqlParameter("@WARRANTY",lstWarranty1[j].ToString()),
                                                               new SqlParameter("@WARRANTYPERIOD",lstWarrantyDetails1[j].ToString())                                                               
                                                           };
                                int intResult = DU.executeprocedure("USP_IVR_SaveTransactionItemDetails", sparam);
                                if (intResult > 0)
                                {
                                    strsql = "Select Ident_Current('IVR_TRAN_ITEMDET') as TIDID";
                                    DataTable DTTranTidid = DU.getdata(strsql);
                                    if (DTTranTidid.Rows.Count > 0)
                                    {
                                        SqlParameter[] sparam1 ={
                                                               new SqlParameter("@TYOFENTRY","1"),
                                                               new SqlParameter("@ENTRYID",tranId.ToString()),
                                                               new SqlParameter("@ITMROWID",DTTranTidid.Rows[0]["TIDID"].ToString()),
                                                               new SqlParameter("@ITMID",ddlItemBillLevel.SelectedValue),
                                                               new SqlParameter("@WHID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATCHID",lstBatchId[j].ToString()),                                                               
                                                               new SqlParameter("@QTYPRIM",(0-Convert.ToDouble(lstLocationQty[j].ToString())).ToString()),                                                              
                                                               new SqlParameter("@RATE_PRIMUNIT",txtRateBillLevel.Text.Trim()),                                                             
                                                               new SqlParameter("@ENTRYDATE",strTransDate)
                                                                };
                                        int Result = DU.executeprocedure("USP_IVR_SaveStockDetails", sparam1);
                                        if (Result > 0)
                                        {
                                            intResult = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (isBatchEnabled(ddlItemBillLevel.SelectedValue) && !isWarrantyEnabled(ddlItemBillLevel.SelectedValue))
                    {
                        List<string> lstLocationId = new List<string>();
                        List<string> lstBatchId = new List<string>();
                        List<string> lstLocationQty = new List<string>();
                        if (hidLocationBillLevel.Value.ToString().Contains("/") && hidLocationBillLevel.Value.ToString().Contains("|"))
                        {
                            string[] strMainArray = hidLocationBillLevel.Value.ToString().Split('/');
                            foreach (string strSubArray in strMainArray)
                            {
                                string[] str = strSubArray.ToString().Split(',');
                                lstLocationId.Add(str[0].ToString());
                                string[] str1 = str[1].ToString().Split('|');
                                lstLocationQty.Add(str1[0].ToString());
                                lstBatchId.Add(str1[1].ToString());
                            }
                        }
                        else
                        {
                            string[] str = hidLocationBillLevel.Value.ToString().Split(',');
                            lstLocationId.Add(str[0].ToString());
                            string[] str1 = str[1].ToString().Split('|');
                            lstLocationQty.Add(str1[0].ToString());
                            lstBatchId.Add(str1[1].ToString());
                        }
                        if (lstLocationId != null)
                        {
                            int Count = Convert.ToInt32(lstLocationId.Count);
                            for (int j = 0; j < Count; j++)
                            {
                                SqlParameter[] sparam ={
                                                               new SqlParameter("@TITID",tranItemId.ToString()),
                                                               new SqlParameter("@WHSID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATID",lstBatchId[j].ToString()),
                                                               new SqlParameter("@DETQTY",lstLocationQty[j].ToString()),
                                                               new SqlParameter("@WARRANTY","0"),
                                                               new SqlParameter("@WARRANTYPERIOD","0")                                                               
                                                           };
                                int intResult = DU.executeprocedure("USP_IVR_SaveTransactionItemDetails", sparam);
                                if (intResult > 0)
                                {
                                    strsql = "Select Ident_Current('IVR_TRAN_ITEMDET') as TIDID";
                                    DataTable DTTranTidid = DU.getdata(strsql);
                                    if (DTTranTidid.Rows.Count > 0)
                                    {
                                        SqlParameter[] sparam1 ={
                                                               new SqlParameter("@TYOFENTRY","1"),
                                                               new SqlParameter("@ENTRYID",tranId.ToString()),
                                                               new SqlParameter("@ITMROWID",DTTranTidid.Rows[0]["TIDID"].ToString()),
                                                               new SqlParameter("@ITMID",ddlItemBillLevel.SelectedValue),
                                                               new SqlParameter("@WHID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATCHID",lstBatchId[j].ToString()),                                                               
                                                               new SqlParameter("@QTYPRIM",(0-Convert.ToDouble(lstLocationQty[j].ToString())).ToString()),                                                              
                                                               new SqlParameter("@RATE_PRIMUNIT",txtRateBillLevel.Text.Trim()),                                                             
                                                               new SqlParameter("@ENTRYDATE",strTransDate)
                                                                };
                                        int Result = DU.executeprocedure("USP_IVR_SaveStockDetails", sparam1);
                                        if (Result > 0)
                                        {
                                            intResult = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (!isBatchEnabled(ddlItemBillLevel.SelectedValue) && !isWarrantyEnabled(ddlItemBillLevel.SelectedValue))
                    {
                        List<string> lstLocationId = new List<string>();
                        List<string> lstLocationQty = new List<string>();
                        if (hidLocationBillLevel.Value.ToString().Contains("/"))
                        {
                            string[] strMainArray = hidLocationBillLevel.Value.ToString().Split('/');
                            foreach (string strSubArray in strMainArray)
                            {
                                string[] str = strSubArray.ToString().Split(',');
                                lstLocationId.Add(str[0].ToString());
                                lstLocationQty.Add(str[1].ToString());
                            }
                        }
                        else
                        {
                            string[] str = hidLocationBillLevel.Value.ToString().Split(',');
                            lstLocationId.Add(str[0].ToString());
                            lstLocationQty.Add(str[1].ToString());
                        }
                        if (lstLocationId != null)
                        {
                            int Count = Convert.ToInt32(lstLocationId.Count);
                            for (int j = 0; j < Count; j++)
                            {
                                SqlParameter[] sparam ={
                                                               new SqlParameter("@TITID",tranItemId.ToString()),
                                                               new SqlParameter("@WHSID",lstLocationId[j].ToString()),                                                               
                                                               new SqlParameter("@DETQTY",lstLocationQty[j].ToString()),
                                                               new SqlParameter("@WARRANTY","0"),
                                                               new SqlParameter("@WARRANTYPERIOD","0")                                                               
                                                           };
                                int intResult = DU.executeprocedure("USP_IVR_SaveTransactionItemDetails", sparam);
                                if (intResult > 0)
                                {
                                    strsql = "Select Ident_Current('IVR_TRAN_ITEMDET') as TIDID";
                                    DataTable DTTranTidid = DU.getdata(strsql);
                                    if (DTTranTidid.Rows.Count > 0)
                                    {
                                        SqlParameter[] sparam1 ={
                                                               new SqlParameter("@TYOFENTRY","1"),
                                                               new SqlParameter("@ENTRYID",tranId.ToString()),
                                                               new SqlParameter("@ITMROWID",DTTranTidid.Rows[0]["TIDID"].ToString()),
                                                               new SqlParameter("@ITMID",ddlItemBillLevel.SelectedValue),
                                                               new SqlParameter("@WHID",lstLocationId[j].ToString()),
                                                               new SqlParameter("@BATCHID","0"),                                                               
                                                               new SqlParameter("@QTYPRIM",(0-Convert.ToDouble(lstLocationQty[j].ToString())).ToString()),                                                              
                                                               new SqlParameter("@RATE_PRIMUNIT",txtRateBillLevel.Text.Trim()),                                                             
                                                               new SqlParameter("@ENTRYDATE",strTransDate)
                                                                };
                                        int Result = DU.executeprocedure("USP_IVR_SaveStockDetails", sparam1);
                                        if (Result > 0)
                                        {
                                            intResult = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    protected void InsertItemTranTotalBillLevel(string strTranId)
    {
        if (strTranId.ToString() != string.Empty)
        {
            int intResult = 0;
            SqlParameter[] sparam ={
                           new SqlParameter("@TRNID",strTranId.ToString()),
                           new SqlParameter("@ITEMTOTAL",txtTotalItemBillLevel.Text.Trim()),
                           new SqlParameter("@ITEMTOTAL_LID",ddlSaleLedger.SelectedValue),
                           new SqlParameter("@TAXABLEAMT",txtTaxableAmtBillLevel.Text.Trim()),
                           new SqlParameter("@TAX_TXMASID",ddlVatBillLevel.SelectedValue),
                           new SqlParameter("@TAXPER",hidTaxRateBillLevelMain.Value.ToString()),
                           new SqlParameter("@TAXAMT",txtVatBillLevel.Text.Trim()),
                           new SqlParameter("@TAXAMT_LID",ddlSaleTaxLedger.SelectedValue),
                           new SqlParameter("@RNDOFFAMT",txtRoundOffBillLevel.Text.Trim()),
                           //new SqlParameter("@RNDOFFAMT_LID",ddlRoundOff.SelectedValue),
                           new SqlParameter("@TRNTOTAL",txtGrandTotalBillLevel.Text.Trim())                                                                                                                 
                       };
            intResult = DU.executeprocedure("USP_IVR_SaveTranTotal", sparam);
        }
    }

    protected void btnSubmit_OnClick(object sender, EventArgs e)
    {
        InsertItemTranMainBillLevel(InsertVouchersBillLevel());
    }
    #endregion

    protected void BindGrdSaleInvoice()
    {

        //strsql = "select (IVR_TRANFORMATNUM.numprefix+'/'+ IVR_TRANFORMAT.FormatName+'/'+ IVR_TRANFORMATNUM.numsuffix) as invoice , ACC_LEDMAST.LNAME, IVR_TRAN_MAIN.TRNDATE from IVR_TRAN_MAIN inner join IVR_TRANFORMAT on (IVR_TRANFORMAT.Trantype = IVR_TRAN_MAIN.Trantypeid) inner join ACC_LEDMAST on (ACC_LEDMAST.LID =IVR_TRAN_MAIN.Vendcust_lid) inner join IVR_TRANFORMATNUM on (IVR_TRANFORMATNUM.tfoid = IVR_TRAN_MAIN.tfoid) where TRANTYPEID='1'";
        
        DataTable dt = DU.getdatausingprocedure("usp_IVR_GetAllSaleinvoice");
        GrdSaleInvoice.DataSource = dt;
        GrdSaleInvoice.DataBind();
    }
}